<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

use yii\helpers\Json;

/* ===================== 动态控件项JS值初始化模板 ===================== */

/** @var \yii\web\View $this View实例 */
/** @var array $controlOptions 控件选项 */
?>
<script>
    /** @var isInit 是否页面初始化 */
    /** @var ueEditor UE实例 */
    /** @var formOptions 表单选项 */

    // 初始化排序
    if (isInit) {
        /**
         * @desc 配置描述
         * @see https://www.jq22.com/jquery-info23053
         * @see https://www.npmjs.com/package/sortablejs?activeTab=readme
         */
        Sortable.create(document.getElementById("<?= $controlOptions['__id'] ?>"), {
            draggable: ".drag-item",
            handle: ".drag-handle",
            // animation: 150,
            animation: 300,
            // easing: "cubic-bezier(1, 0, 0, 1)",
            easing: "linear",
            // 结束拖拽
            onEnd: function( /**Event*/ evt) {
                var oldIndex = evt.oldIndex;
                var newIndex = evt.newIndex;
                if (oldIndex !== newIndex) {
                    var list = $scope.<?= $controlOptions['__scope'] ?>;
                    var newList = [];
                    var changeItem = list[oldIndex];
                    list.forEach(function (value, index) {
                        if (oldIndex === index) { return; }
                        if (oldIndex > newIndex && newIndex === index) { newList.push(changeItem); }
                        newList.push(value);
                        if (oldIndex < newIndex && newIndex === index) { newList.push(changeItem); }
                    });

                    $scope.$apply(function () {
                        $scope.<?= $controlOptions['__scope'] ?> = [];
                        $timeout(function () {
                            //下一个宏任务执行编译
                            $scope.<?= $controlOptions['__scope'] ?> = newList;
                        });
                    });

                }

            },
        });
    }

    // 动态控件默认值
    $scope.<?= $controlOptions['__scope'] ?> = <?= Json::encode($controlOptions['__default']) ?>;
</script>
